package org.ef.anticheck;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * 本地 Query，从本地数据库查询
 * 
 * @author zenglu.liu
 */
public class LocalQuery implements Query {

	private final SQLiteDatabase db;

	private final String tableName;

	public LocalQuery(final SQLiteDatabase db, final String tableName) {
		this.db = db;
		this.tableName = tableName;
	}

	public Recoder execute(final String phone) throws QueryException {
		final Cursor cursor = this.db.query(this.tableName, null,
				"phone_number = ?", new String[] { phone }, null, null, null,
				null);

		if (cursor == null) {
			return null;
		}

		if ((cursor.getCount() <= 0) || !cursor.moveToFirst()) {
			cursor.close();
			return null;
		}

		final Recoder r = new Recoder();

		r.id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
		r.phone = cursor.getString(cursor.getColumnIndexOrThrow("phone_number"));
		r.info = cursor.getString(cursor.getColumnIndexOrThrow("region"))
				+ cursor.getString(cursor.getColumnIndexOrThrow("service_providers"))
				+ cursor.getString(cursor.getColumnIndexOrThrow("message"));

		cursor.close();

		return r;
	}

	public void dispose() {
		this.db.close();
	}
}
